#
# tloader.py
#
#
# PyEMOF: An EMOF support for Python
#
# Copyright (C) 2004, 2007 Raphael Marvie 
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.
# http://www.fsf.org/licensing/licenses/gpl.html
#
# Author contact: raphael.marvie@lifl.fr
#
# Modified and adapted to conform with ECORE 2.0 by brenomachado@gmail.com


'''
Templates for the generation of Loader utility for repository
generated used PyEMOF.
'''

__author__  = 'Raphael Marvie <raphael.marvie@lifl.fr> / Breno Batista Machado <brenomachado@gmail.com>'
__date__    = '2008-03-16'
__version__ = '0.7.0'

class tstr:
    pass

class tmpl:
    
    file_header = """# -*- coding: utf-8 -*-
#
# loader.py

from xml.dom import minidom

%(modules_imports)s

def gen():
    i = 0
    while True:
        yield i
        i += 1

x = gen()

class LoadElement (object):

    def __init__(self, post, ids, fact):
        super(LoadElement, self).__init__()
        self._post = post
        self._ids = ids

    def create(self, elt):
        pass

    def process(self, obj, elt):
        pass

    def __call__(self, elt):
        obj = self.create(elt)
        self._post['stack'].append(obj._xmi_id)
        self.process(obj, elt)
        self._post['stack'].remove(obj._xmi_id)
        return obj
"""
    
    import_template = """import %(module)s"""

    load_dict = """
loaders = {
%(values)s    
}
"""

    loader_class = """

class Loader (object):
    '''%(name)s model loader from an XMI file to a repository.'''

    def __init__(self):
        super(Loader, self).__init__()
        self._post = dict()
        self._post['append'] = list()
        self._post['set'] = list()
        self._post['stack'] = list()
        self._ids = dict()

    def _postprocessing(self):
        for obj, attr, id_ in self._post['append']:
            a = getattr(obj, attr)
            a.append(self._ids[id_])
        for obj, attr, id_ in self._post['set']:
            setattr(obj, attr, self._ids[id_])

    def load(self, str):
        doc = minidom.parseString(str)
        xmi = doc.documentElement
        assert xmi.nodeName == 'xmi:XMI', 'Bad file format'
        rep = %(name)s.core.Repository()
        fact = %(name)s.core.Factory(rep)
        elt = xmi.firstChild
        while elt:
            if elt.nodeName == u'xmi:Extension':
                pass
            elt = elt.nextSibling"""

    loader_main_body = """
        elt = xmi.firstChild
        while elt:
            if elt.nodeName == u'%(prefix)s:%(name)s':
                obj = %(name)s(self._post, self._ids, fact)(elt)
            elt = elt.nextSibling"""

    loader_main_end = """
        self._postprocessing()
        return rep
"""

    load_primitive = """

class %(name)s (LoadElement):

    def __init__(self, post, ids, fact):
        super(%(name)s, self).__init__(post, ids, fact)
        self.fact = fact

    def create(self, elt):
        obj = self.fact.%(module)screate_%(name)s()
        obj._xmi_id = elt.getAttribute('xmi:id')
        self._ids[obj._xmi_id] = obj
        if len(obj._xmi_id.split(":")) > 1:
            obj._id = obj._xmi_id.split(":")[1]
        else:
            obj._id = x.next()
        return obj
        
    def process(self, obj, elt):
        super(Element, self).process(obj, elt)
"""

    load_element_begin = """

class %(name)s (%(super)s):

    def __init__(self, post, ids, fact):
        super(%(name)s, self).__init__(post, ids, fact)
        self.fact = fact

    def create(self, elt):
        obj = self.fact.%(module)screate_%(name)s()
        obj._xmi_id = elt.getAttribute('xmi:id')
        self._ids[obj._xmi_id] = obj
        if len(obj._xmi_id.split(":")) > 1:
            obj._id = obj._xmi_id.split(":")[1]
        else:
            obj._id = x.next()
        return obj

    def process(self, obj, elt):
        super(%(name)s, self).process(obj, elt)"""

    load_mult_composite = """
        e = elt.firstChild
        while e:
            if e.nodeName == u'%(xname)s':
                clss = loaders[e.getAttribute('xmi:type')]
                o = clss(self._post, self._ids, self.fact)(e)
                obj.%(iname)s.append(o)
            e = e.nextSibling"""

    load_mult_attribute = """
        e = elt.firstChild
        while e:
            if e.nodeName == u'%(xname)s':
                id = e.getAttribute('idref')
                self._post['append'].append((obj, '%(iname)s', id))
            e = e.nextSibling"""

    load_attribute = """
        if elt.getAttribute('%(xname)s'):
            obj.%(iname)s = elt.getAttribute('%(xname)s')"""

    load_attr_typed = """
        id = elt.getAttribute('%(xname)s')
        if id:
            self._post['set'].append((obj, '_%(iname)s', id))"""

    load_element_end = """
"""

    file_footer = """
# eof
"""
